package com.atguigu.gulimall.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.fastjson.JSON;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author 马迎迎
 * @Title: SentinelGatewayConfig
 * @Package com.atguigu.gulimall.gateway.config
 * @Description: TODO(添加描述)
 * @date 2021年06月04日 9:58
 */
@Configuration
public class SentinelGatewayConfig {

    //GatewayCallbackManager
    //TODO web响应式编程 天然支持大并发系统
    public SentinelGatewayConfig(){
        GatewayCallbackManager.setBlockHandler(new BlockRequestHandler() {
            //网关限流了请求，就会返回此回调 Mono返回0/1个数据 Flux返回0、多个数据 响应式编程，承受高并发
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
                R error = R.error(BizCodeEnum.TOO_MANY_REQUEST.getCode(), BizCodeEnum.TOO_MANY_REQUEST.getMsg());
                String jsonString = JSON.toJSONString(error);

//                Mono.just(jsonString)
                Mono<ServerResponse> body = ServerResponse.ok().body(Mono.just(jsonString), String.class);
                return body;
            }
        });
    }
}
